package com.ubao.ui.pullToRefreshListView;

import android.graphics.Point;
import android.util.Log;

public class RangeUtils {
	// ÿҳ����
	int pageSize = 20;
	// �������
	int MAX_COUNT = 80;
	static RangeUtils ru;
	int startCount;
	int endCount;
	static Object lock = new Object();

	public static RangeUtils getInstance(int pageSize, int maxCount) {
		synchronized (lock) {
			if (ru == null) {
				ru = new RangeUtils(pageSize, maxCount);
			}
		}

		return ru;
	}

	public static RangeUtils getInstance() {
		synchronized (lock) {
			if (ru == null) {
				ru = new RangeUtils();
			}
		}
		return ru;
	}

	public static void reSet() {
		ru = null;
	}

	public boolean isBottom() {
		return endCount == MAX_COUNT ? true : false;
	}

	public boolean isTop() {
		return startCount <= 0 ? true : false;
	}

	private RangeUtils() {
		pageSize = 20;
		startCount = 0 - pageSize;
		endCount = 0 + pageSize;
	}

	private RangeUtils(int pageSize, int maxCount) {
		this.pageSize = pageSize;
		this.MAX_COUNT = maxCount;
		startCount = 0 - pageSize;
		endCount = 0 + pageSize > MAX_COUNT ? MAX_COUNT : pageSize;

	}

	/**
	 * ��һҳ
	 * */
	public Point getDown() {
		if (isOutOfRange(endCount + pageSize)) {
			endCount = MAX_COUNT;
			startCount = endCount - pageSize * 2 > 0 ? endCount - pageSize * 2
					: 0;
		} else {
			startCount += pageSize;
			endCount += pageSize;
		}
		Point pb = new Point(startCount, endCount);
		return pb;
	}

	/**
	 * ��һҳ
	 * */
	public Point getUp() {
		if (startCount == 0) {
			return new Point(startCount, endCount);
		}

		if (isOutOfRange(startCount - pageSize)) {
			int size = startCount - 0;
			// endCount = startCount-1;
			startCount = 0;
			endCount = pageSize * 2 > MAX_COUNT ? MAX_COUNT : pageSize * 2;

			if (endCount != MAX_COUNT)
				Log.e("endCount_error", "MAX_COUNT:" + MAX_COUNT + " end:"
						+ endCount);

		} else {

			startCount -= pageSize;
			endCount = startCount + pageSize * 2 > MAX_COUNT ? MAX_COUNT
					: startCount + pageSize * 2;

		}
		Point pb = new Point(startCount, endCount);
		return pb;
	}

	public Point getCurrent() {
		return new Point(startCount > 0 ? startCount : 0,
				endCount > MAX_COUNT ? MAX_COUNT : endCount);
	}

	public boolean isOutOfRange(int x) {
		return x > MAX_COUNT ? true : x < 0 ? true : false;
	}

	public int measurePos(int position) {
		// TODO Auto-generated method stub
		return position + (startCount < 0 ? 0 : startCount);
	}

	public Point delete() {
		MAX_COUNT--;
		if (endCount > MAX_COUNT) {
			endCount = MAX_COUNT;
			if (endCount == startCount) {
				return getUp();
			}
			return null;
		} else {
			return getCurrent();
		}

	}

}
